package com.thememaker.lockstyle.control;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXCheckBox;
import com.jfoenix.controls.JFXRadioButton;
import com.jfoenix.controls.JFXSlider;
import com.jfoenix.svg.SVGGlyph;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.ui.CtsFileChooser;
import com.thememake.ui.Toast;
import com.thememake.ui.dialog.SBTFxDialog;
import com.thememake.util.FileUtils;
import com.thememake.util.HanYuUtils;
import com.thememaker.lockstyle.LockstyleShowUtils;
import com.thememaker.lockstyle.bean.Lockscreen;
import com.thememaker.lockstyle.bean.ui.BaseView;
import com.thememaker.util.SVGLoadUtils;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import com.thememake.ui.dialog.ProgressDialog;
import org.w3c.dom.Document;

import java.awt.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.thememaker.lockstyle.LockstyleMainController.buttonColor;

public class LayoutComponentUtils {
    public static boolean content_Determine = true;
    public static boolean head_judge = true;
    public  static int screen_heigth=1920;
    private static LayoutComponentUtils layoutComponentUtils;
    private static Stage primaryStage = new Stage();
    public static int engine = 1;//1掌酷 ，2微乐 ， 3oppo
    public static Path lockscreenPath ;
    private List<String> previewItemList = new ArrayList<>();
    public  static int  bgNum = 1;
    public static List<String> bgsPath = new ArrayList<>();
//    public static Document document ;
//    public static ThemeFileInfo themeFileInfo;
    public static LockstyleShowUtils lockstyleShowUtils;
    private LayoutComponentUtils() {

    }
    public static List<String> fitList = new ArrayList<>();
    public static boolean  switcheTime = true;
    public static int patternID = 1;
    public static LayoutComponentUtils getInstance() {
        if (layoutComponentUtils == null) {
            layoutComponentUtils = new LayoutComponentUtils();
        }
        return layoutComponentUtils;
    }

    public VBox getControlView(double width, double height) {
        VBox vBox = new VBox();
        vBox.setPrefWidth(width);
        vBox.setPrefHeight(height);
        vBox.getStylesheets().add("style/lockstylemain.css");
        vBox.setPadding(new Insets(10, 10, 10, 10));
        vBox.setSpacing(10);
        vBox.setAlignment(Pos.TOP_LEFT);
        vBox.setStyle("-fx-background-color: white;-fx-background-radius: 5;-fx-border-radius: 5;-fx-effect: dropshadow( gaussian , #E8E8EA , 10,0.6,0,1 );");
        vBox.getStyleClass().addAll("custom-color-dialog");
        return vBox;
    }

    public Label getControlTitleLabel(String titleName) {
        return getControlLabel(titleName, 16);
    }

    public Label getControlNormalLabel(String labelString) {
        return getControlLabel(labelString, 12);
    }

    private Label getControlLabel(String labelString, double fontSize) {
        Label label = new Label();
        label.setText(labelString);
        label.setAlignment(Pos.CENTER);
        label.setId("diy-fontColor");
        label.setFont(new Font(fontSize));
        return label;
    }

    public Node getControlLabelField(String labelText, String fieldText, double fieldWidth, boolean fieldEditable) {
        HBox hBox = new HBox();
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.getChildren().addAll(getControlNormalLabel(labelText), getControlTextField(fieldText, fieldWidth, fieldEditable));
        return hBox;
    }

    public JFXRadioButton getControlRadioButton(String content, double width, ToggleGroup toggleGroup, boolean select) {
        JFXRadioButton radioButton = new JFXRadioButton(content);
        radioButton.setPrefWidth(width);
        radioButton.setToggleGroup(toggleGroup);
        radioButton.setSelected(select);
        return radioButton;
    }

    public TextField getControlTextField(String content, double width, boolean editable) {
        TextField textField = new TextField();
        textField.setText(content);
        textField.setId("diy-textfield");
        textField.setFont(new Font(12));
        textField.setEditable(editable);
        textField.setPrefWidth(width);
        return textField;
    }

    public StackPane getWallpaperPane(Path lockscreenPath,String wallpaperString, double importWidth, double importHeight, Consumer<Path> consumer) {
        StackPane stackPane = getImagePane(lockscreenPath,216, 480, wallpaperString, importWidth, importHeight, true, consumer);
        return stackPane;
    }

    public StackPane getImagePane(Path lockscrenPath,int width, int height, String imageFileString, double importWidth, double importHeight, boolean checkSize, Consumer<Path> consumer) {
        final StackPane stackPane = new StackPane();
        stackPane.setPrefWidth(width);
        stackPane.setPrefHeight(height);
        stackPane.setMaxWidth(width);
        stackPane.setMaxHeight(height);
        stackPane.getStyleClass().addAll("color-rect", "transparent-pattern");
        stackPane.setAlignment(Pos.CENTER);

        JFXButton bottomBtn = new JFXButton("添加");
        bottomBtn.setButtonType(JFXButton.ButtonType.FLAT);
        bottomBtn.setPrefWidth(width);
        bottomBtn.setPrefHeight(25);
        bottomBtn.setDisableVisualFocus(true);
        StackPane.setMargin(bottomBtn, new Insets(height - 30, 0, 0, 0));
        bottomBtn.setStyle("-fx-text-fill:WHITE;-fx-background-color:rgb(0,0,0,0.4);-fx-font-size:14px;");
        ImageView imageView = new ImageView();
        Optional.ofNullable(Optional.ofNullable(imageFileString)
                .map(pathStr -> Paths.get(pathStr))
                .filter(path -> Files.exists(path)).orElse(null)).ifPresent(path -> {
            Image image = new Image(path.toUri().toString(), width, height, true, false, true);
            imageView.setImage(image);
            imageView.setSmooth(true);
            imageView.setPreserveRatio(true);
            bottomBtn.setText("替换");
        });


        stackPane.getChildren().add(imageView);
        bottomBtn.setVisible(false);
        stackPane.getChildren().add(bottomBtn);
        stackPane.addEventHandler(MouseEvent.MOUSE_ENTERED, event -> {
            bottomBtn.setVisible(true);
        });
        //鼠标离开区域
        stackPane.addEventHandler(MouseEvent.MOUSE_EXITED, event -> {
            bottomBtn.setVisible(false);
        });
        //设置鼠标样式
        bottomBtn.addEventHandler(MouseEvent.MOUSE_ENTERED, event -> {
            bottomBtn.setCursor(Cursor.HAND);
        });
        bottomBtn.addEventHandler(MouseEvent.MOUSE_EXITED, event -> {
            bottomBtn.setCursor(Cursor.DEFAULT);
        });
        bottomBtn.setOnAction(event -> {
//            FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter("PNG,JPEG File", "*.png", "*.jpg");
//            if (imageFileString.endsWith(".png")) {
//                extensionFilter = new FileChooser.ExtensionFilter("PNG File", "*.png");
//            } else if (imageFileString.endsWith(".jpg")) {
//                extensionFilter = new FileChooser.ExtensionFilter("JPEG File", "*.jpg");
//            }
            FileChooser.ExtensionFilter extensionFilter = Optional.ofNullable(getExtensionFilterStrByImageFileString(imageFileString))
                    .map(extension -> new FileChooser.ExtensionFilter(getDescriptionByExtension(extension), extension))
                    .orElse(new FileChooser.ExtensionFilter("PNG,JPEG File", "*.png", "*.jpg"));
            Optional.ofNullable(CtsFileChooser.getInstance().showOpenDialog(null, "选择图片", extensionFilter))
                    .ifPresent(file -> {
//                        String endString = file.getName().substring(file.getName().lastIndexOf("."));
//                        System.err.println("file >>>" + file.getName().replace(endString,""));
                        Path imagePath = Optional.ofNullable(imageFileString)
                                .map(imageStr -> Paths.get(imageFileString))
                                .orElse(Paths.get(lockscrenPath.toString(),getImageName(file.getName())));
                        Image image = new Image(file.toPath().toUri().toString());
                        if (checkSize) {
                            if (image.getWidth() == importWidth && image.getHeight() == importHeight) {
                                if (importWidth == 1080 && importHeight == 2400){
                                    imagePath = Paths.get(lockscrenPath.toString(),"default_lock_wallpaper_2400.jpg");
                                }
                                updateImagePane(file, imagePath, stackPane, width, height);
                            } else {
                                Toast.makeText(new Stage(), "图片尺寸不符,请选择 " + (int) importWidth + "*" + (int) importHeight + " 大小的图片", 2000);
                            }
                        } else {
                            updateImagePane(file, imagePath, stackPane, width, height);
                        }
                        image.cancel();
                        consumer.accept(imagePath);
                    });
//            File chooserFile = CtsFileChooser.getInstance().showOpenDialog(null, "选择图片", extensionFilter);
//            if (chooserFile != null) {
//                Image image = new Image(chooserFile.toPath().toUri().toString());
//                if (checkSize) {
//                    if (image.getWidth() == importWidth && image.getHeight() == importHeight) {
//                        updateImagePane(chooserFile, imagePath, stackPane, width, height);
//                    } else {
//                        Toast.makeText(new Stage(), "图片尺寸不符,请选择 " + (int) importWidth + "*" + (int) importHeight + " 大小的图片", 2000);
//                    }
//                } else {
//                    updateImagePane(chooserFile, imagePath, stackPane, width, height);
//                }
//                image.cancel();
//            }
        });
        return stackPane;
    }

    private String getImageName(String nameString){
        StringBuffer stringBuffer = new StringBuffer();
        HanYuUtils hanYuUtils = new HanYuUtils();
        for (char c:nameString.toCharArray()){
            System.err.println("C >>> " + String.valueOf(c));
            stringBuffer.append(Optional.of(isChinese(String.valueOf(c))).filter(b -> b).map(b-> hanYuUtils.getStringPinYin(String.valueOf(c))).orElse(String.valueOf(c)));
        }
        return stringBuffer.toString();
    }

    public static boolean isChinese(String str) {
        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(str);
        return matcher.find();
    }

    private String getExtensionFilterStrByImageFileString(String imageFileString) {
        return Optional.ofNullable(imageFileString)
                .filter(fileStr -> fileStr.lastIndexOf(".") > 0)
                .map(fileStr -> "*" + fileStr.substring(fileStr.lastIndexOf(".")))
                .orElse(null);
    }

    private String getDescriptionByExtension(String extension) {
        Optional<String> pngOptional = Optional.ofNullable(extension).filter(str -> str.endsWith(".png")).map(str -> "PNG File");
        Optional<String> jpgOptional = Optional.ofNullable(extension).filter(str -> str.endsWith(".jpg")).map(str -> "JPEG File");
        return pngOptional.orElse(jpgOptional.orElse("PNG,JPEG File"));
//        return Optional.ofNullable(extension)
//                .filter(str -> str.lastIndexOf(".") >=0 )
//                .map(str->str.substring(str.lastIndexOf(".")).toUpperCase() + " File")
//                .orElse("PNG,JPEG File");

//        if (extension.endsWith(".png")) {
//            return "PNG File";
//        } else if (extension.endsWith(".jpg")) {
//            return "JPEG File";
//        }
//        return "PNG,JPEG File";
    }

    private void updateImagePane(File chooserFile, Path imagePath, StackPane stackPane, int width, int height) {
        try {
            FileUtils.copyFile(chooserFile.toPath(), imagePath, true);
            ImageView imageView = (ImageView) stackPane.getChildren().get(0);
            imageView.setImage(new Image(imagePath.toUri().toString(), width, height, true, false, true));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public FlowPane getImageListPane(String lockscreenPath,String src,String[] srcid,Consumer<Path> consumer){
        FlowPane flowPane = new FlowPane();
        flowPane.setHgap(18);
        flowPane.setVgap(18);
        flowPane.setPadding(new Insets(10));
        Button but1 = new Button("批量导入");
        Button btn_out1 = new Button("批量导出");
        but1.setId("diy-button");
        btn_out1.setId("diy-button");
        but1.setMinHeight(25);
        btn_out1.setMinHeight(25);
        but1.setMinWidth(66);
        btn_out1.setMinWidth(66);
        HBox btn = new HBox();
        btn.setSpacing(25);
        btn.setPrefWidth(1030);
        btn.getChildren().addAll(but1,btn_out1);
        flowPane.getChildren().add(btn);
        createFlowPaneItem(srcid,lockscreenPath,src,consumer,flowPane);
        but1.setOnAction(event -> {
            File imgpath = CtsFileChooser.getInstance().showOpenDirDialog(null, "批量导入预览图");
            List<String> importNames = new ArrayList<>();
            StringBuffer message = new StringBuffer("批量导入成功，具体如下：\n");
            if (imgpath != null) {
                ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        previewItemList = new ArrayList<>();
                        for(int i = 0;i<srcid.length;i++){
                            if (srcid[i].equals("dot")){
                                String imgname = src.split("/")[1].replace(".png", "_dot.png")
                                        .replace(".jpg", "_dot.jpg");
                                previewItemList.add(imgname);
                            }else{
                                String imgname = src.split("/")[1].replace(".png", "_" + srcid[i] + ".png")
                                        .replace(".jpg", "_" + srcid[i] + ".jpg");
                                previewItemList.add(imgname);
                            }
                        }
                        if (previewItemList != null && previewItemList.size() > 0) {
                            for (String previewItem : previewItemList) {
                                Path importPath = Paths.get(imgpath.getPath(), previewItem);
                                if (Files.exists(importPath)) {
                                    FileUtils.copyFile(importPath, Paths.get(lockscreenPath+"\\"+src.split("/")[0]+"\\"+previewItem), true);
                                    importNames.add(previewItem);
                                    message.append(previewItem + "\n");
                                }
                            }
                        }
                        return null;
                    }
                }, primaryStage, "正在导入，请稍等……");
                progressFrom.showProgressBar(() -> {
                    Platform.runLater(() -> {
                        if (importNames.size() > 0) {
                            SBTFxDialog.showMessageDialog(primaryStage, message.toString(), "温馨提示", new SBTFxDialog.ClickListen() {
                                @Override
                                public void onCloseClick() {
                                   flowPane.getChildren().clear();
                                   flowPane.getChildren().add(btn);
                                   createFlowPaneItem(srcid,lockscreenPath,src,consumer,flowPane);
                                   consumer.accept(imgpath.toPath());
                                }
                            });
                        } else {
                            Toast.makeText(primaryStage, "没有可用的预览图，请选择正确的文件夹", 1000);
                        }
                    });
                });
            }
        });
        btn_out1.setOnAction(event -> {
            File pathout = CtsFileChooser.getInstance().showOpenDirDialog(null, "批量导出预览图");
            if (pathout != null) {
                ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        previewItemList = new ArrayList<>();
                        for(int i = 0;i<srcid.length;i++){
                            if (srcid[i].equals("dot")){
                                String imgname = src.split("/")[1].replace(".png", "_dot.png")
                                        .replace(".jpg", "_dot.jpg");
                                previewItemList.add(imgname);
                            }else{
                                String imgname = src.split("/")[1].replace(".png", "_" + srcid[i] + ".png")
                                        .replace(".jpg", "_" + srcid[i] + ".jpg");
                                previewItemList.add(imgname);
                            }
                        }
                        if (previewItemList != null && previewItemList.size() > 0) {
                            for (String previewItem : previewItemList) {
                                try {
                                        Path previewPath = Paths.get(lockscreenPath+"\\"+src.split("/")[0], previewItem);
                                        System.err.println("previewPath >>> " + previewPath.toString());
                                        if (Files.exists(previewPath)) {
                                            FileUtils.copyFile(previewPath, Paths.get(pathout.getPath(), previewItem), true);
                                        }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        return null;
                    }
                }, primaryStage, "正在导出，请稍等……");
                progressFrom.showProgressBar(() -> {
                    Toast.makeText(primaryStage, "导出成功", 1000);
                    EventQueue.invokeLater(() -> {
                        try {
                            Desktop.getDesktop().open(pathout);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                });
            } else {
                Toast.makeText(primaryStage, "请选择需要导出的目录", 1000);
            }
        });
        return flowPane;
    }

    private void createFlowPaneItem(String[] srcid,String lockscreenPath,String src,Consumer<Path> consumer,FlowPane flowPane){
        final int ITEMS = srcid.length;
        Path path;
        for(int i = 0;i<ITEMS;i++){
            path = Paths.get(lockscreenPath, src);
            path = Paths.get(path.toString()
                    .replace(".png", "_" + srcid[i] + ".png")
                    .replace(".jpg", "_" + srcid[i] + ".jpg"));
            VBox vBox = new VBox();
            Label label;
            Label imgtype;
            if (srcid[i].equals("dot")){
                label = new Label("中间符号");
                label.setId("diy-fontColor");
                String imgname = src.split("/")[1].replace(".png", "_dot.png")
                        .replace(".jpg", "_dot.jpg");
                imgtype = new Label("图片："+imgname);
            }else{
                label = new Label("数字："+i);
                String imgname = src.split("/")[1].replace(".png", "_" + srcid[i] + ".png")
                        .replace(".jpg", "_" + srcid[i] + ".jpg");
                imgtype = new Label( "图片："+imgname);

            }
            label.setId("diy-fontColor");
            imgtype.setId("diy-fontColor");
            vBox.getChildren().addAll(LayoutComponentUtils.getInstance().getImagePane(Paths.get(lockscreenPath),100, 100,
                    path.toString(),
                    0, 0, false, consumer),label,imgtype);
            flowPane.getChildren().add(vBox);
        }
    }


    public Node getEditTitleHbox(String titleName, BiConsumer<Button,Button> editEvent, BiConsumer<Button,Button>  saveEvent) {
        HBox hBox = new HBox();
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.setSpacing(20);
        hBox.getChildren().add(LayoutComponentUtils.getInstance().getControlTitleLabel(titleName));
        Button editButton = new Button("编辑");
        editButton.setId("diy-button");
        editButton.setGraphic(SVGLoadUtils.getInstance().getEditSVG(12, buttonColor));
        Button saveButton = new Button("确定");
        saveButton.setId("diy-button");
        saveButton.setGraphic(SVGLoadUtils.getInstance().getSaveSVG(12, buttonColor));
        hBox.getChildren().add(editButton);
        hBox.getChildren().add(saveButton);
        saveButton.setVisible(false);
        editButton.setOnAction(event -> {
//            saveButton.setVisible(true);
//            editButton.setVisible(false);
            editEvent.accept(editButton,saveButton);
        });
        saveButton.setOnAction(event -> {
            saveEvent.accept(editButton,saveButton);
//            editButton.setVisible(true);
//            saveButton.setVisible(false);
        });
        return hBox;
    }


    public JFXCheckBox getCheckBox(String lableText){
        JFXCheckBox jfxCheckBox = new JFXCheckBox();
        jfxCheckBox.setText(lableText);
        jfxCheckBox.setCheckedColor(buttonColor);
        jfxCheckBox.setUnCheckedColor(buttonColor);
        jfxCheckBox.setTextFill(buttonColor);
        jfxCheckBox.setTextAlignment(TextAlignment.LEFT);
        return jfxCheckBox;
    }

    public HBox getSlideBarHbox(String labelText,int value,int minSize,int maxSize,ChangeListener<Number> changeListener){
        HBox hBox = new HBox();
        hBox.setPadding(new Insets(15,0,0,0));
        hBox.setSpacing(10);
        hBox.getChildren().add(getControlNormalLabel(labelText));
        Label label = getControlNormalLabel(value+"");
        JFXSlider jfxSlider = new JFXSlider();
        jfxSlider.setId("jfx-slider-colored");
        jfxSlider.setMax(maxSize);
        jfxSlider.setMin(minSize);
        jfxSlider.setPrefWidth(200);
        jfxSlider.setValue(value);
        jfxSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
            label.setText(newValue.intValue()+"");
            changeListener.changed(observable, oldValue, newValue);
        });
        hBox.getChildren().add(jfxSlider);
        hBox.getChildren().add(label);
        return hBox;
    }

    private void addBg(){


    }


}
